package com.qsdjf.fp.weixin.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qsdjf.fp.weixin.cache.TokenCache;
import com.qsdjf.fp.weixin.configuration.properties.Config;
import com.qsdjf.fp.weixin.model.JsToken;
import com.wangzhangxing.cornerstone.common.response.Result;

/**
 * 微信jstoken刷新
 * 
 * @author wangzhangxing
 * @version 1.0
 * @since 2016年6月12日
 */
@RestController
public class JsWeixinController {

	private Logger logger = LoggerFactory.getLogger(JsWeixinController.class);

	@Autowired
	private Config config;

	@RequestMapping(value = "/jsToken", produces = "application/json;charset=utf-8")
	public Object getJsToken(String url) {
		Result<JsToken> result = new Result<JsToken>();
		try {
			url = URLDecoder.decode(url, "utf-8");
			JsToken token = createJsToken(url);
			result.setData(token);
		} catch (IOException e) {
			result.setStatus(-1);
			result.setMessage("获取jsToken失败");
			logger.error("获取jsToken失败", e);
		}
		return result;
	}

	private JsToken createJsToken(String url) throws ClientProtocolException, IOException {
		JsToken token = new JsToken();
		token.setAppId(config.getAppid());
		token.setAccessToken(config.getAppsecret());
		token.setTimestamp(String.valueOf(new Long(System.currentTimeMillis() / 1000l).intValue()));
		token.setNoncestr(UUID.randomUUID().toString().replace("-", ""));
		getAccessTokenAndJsTicket(token);
		buildSignature(token, url);
		return token;
	}

	private void buildSignature(JsToken token, String url) {
		Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		map.put("timestamp", token.getTimestamp());
		map.put("noncestr", token.getNoncestr());
		map.put("jsapi_ticket", token.getJsapiTicket());
		map.put("url", url);
		StringBuilder source = new StringBuilder();
		for (Entry<String, String> e : map.entrySet()) {
			source.append(e.getKey()).append("=").append(e.getValue()).append("&");
		}
		source.deleteCharAt(source.length() - 1);
		token.setSignature(DigestUtils.sha1Hex(source.toString()));
	}

	private void getAccessTokenAndJsTicket(JsToken token) throws ClientProtocolException, IOException {
		token.setAccessToken(TokenCache.getAccessToken());
		token.setJsapiTicket(TokenCache.getJsapiTicket());
	}
}
